<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Form, Field, Button, CellGroup, Toast, Empty, Dialog } from 'vant'
import { productsApi, type Product } from '../api/products'

const products = ref<Product[]>([])
const form = ref<Product>({ name: '', price: 0, stock: 0 })
// 编辑弹窗所用表单
const showEdit = ref(false)
const editForm = ref<Product>({ ID: 0, name: '', price: 0, stock: 0 })

const nameErr = computed(() => !form.value.name ? '请填写名称' : '')
const priceErr = computed(() => form.value.price < 0 ? '价格不能为负数' : '')
const stockErr = computed(() => form.value.stock < 0 ? '库存不能为负数' : '')
const formValid = computed(() => !nameErr.value && !priceErr.value && !stockErr.value)
const submitting = ref(false)

async function load() {
  try {
    const { data } = await productsApi.getList()
    products.value = data
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '加载失败'
    Toast.fail(msg)
  }
}

async function create() {
  // 具体的字段验证提示
  if (!form.value.name.trim()) { 
    Toast.fail('请填写名称'); 
    return 
  }
  if (form.value.price < 0) { 
    Toast.fail('价格不能为负数'); 
    return 
  }
  if (form.value.stock < 0) { 
    Toast.fail('库存不能为负数'); 
    return 
  }
  
  try {
    submitting.value = true
    await productsApi.create(form.value)
    form.value = { name: '', price: 0, stock: 0 }
    await load()
    Toast.success('创建成功')
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '创建失败'
    Toast.fail(msg)
  } finally {
    submitting.value = false
  }
}

onMounted(load)
</script>

<template>
  <div class="page">
    <h2>产品</h2>

    <Form @submit.prevent="create">
      <CellGroup inset>
        <Field v-model.trim="form.name" label="名称" placeholder="请输入名称" :error-message="nameErr" />
        <Field v-model.number="form.price" type="number" label="价格" placeholder="请输入价格" :error-message="priceErr" />
        <Field v-model.number="form.stock" type="number" label="库存" placeholder="请输入库存" :error-message="stockErr" />
      </CellGroup>
      <div style="padding:12px;">
        <Button type="primary" round block native-type="submit" :disabled="submitting">{{ submitting ? '提交中…' : '新增' }}</Button>
      </div>
    </Form>

    <div class="table">
      <div class="t-head">
        <div class="col id">ID</div>
        <div class="col name">名称</div>
        <div class="col price">价格</div>
        <div class="col stock">库存</div>
        <div class="col ops">操作</div>
      </div>
      <div v-if="products.length === 0" style="padding: 12px;">
        <Empty description="暂无数据" />
      </div>
      <div class="t-row" v-for="p in products" :key="p.ID">
        <div class="col id">{{ p.ID }}</div>
        <div class="col name">{{ p.name }}</div>
        <div class="col price">{{ p.price }}</div>
        <div class="col stock">{{ p.stock }}</div>
        <div class="col ops">
          <Button size="small" @click="() => { editForm = { ...p } as any; showEdit = true as any }">编辑</Button>
        </div>
      </div>
    </div>

    <Dialog v-model:show="showEdit" show-cancel-button title="编辑产品" @confirm="async () => {
      if (!editForm?.ID || !editForm?.name || (editForm?.price ?? 0) < 0 || (editForm?.stock ?? 0) < 0) { Toast.fail('请检查表单'); return false }
      try {
        await productsApi.update((editForm as any).ID, { name: (editForm as any).name, price: (editForm as any).price, stock: (editForm as any).stock })
        Toast.success('已保存')
        showEdit = false as any
        await load()
      } catch {}
    }">
      <div style="padding: 0 12px 12px;">
        <CellGroup>
          <Field v-model.trim="(editForm as any).name" label="名称" />
          <Field v-model.number="(editForm as any).price" type="number" label="价格" />
          <Field v-model.number="(editForm as any).stock" type="number" label="库存" />
        </CellGroup>
      </div>
    </Dialog>
  </div>
 </template>

<style scoped>
.page { padding-bottom: 16px; }
.table { border: 1px solid #eee; border-radius: 8px; overflow: hidden; margin-top: 12px; }
.t-head, .t-row { display: grid; grid-template-columns: 120px 1fr 1fr 1fr 140px; }
.t-head { background: #fafafa; font-weight: 600; }
.col { padding: 10px 12px; border-bottom: 1px solid #eee; }
.id { color: #555; }
.name { color: #222; }
.price, .stock { color: #333; }
</style>
